﻿using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CompactMapper.Orm.Annotations;
using CompactMapper.Orm.Contracts;
using CompactMapper.Orm.UnitOfWork.Mappings;
using System.Collections.Generic;
using System;

namespace CompactMapper.Orm.Tests
{
    [TestClass]
    public class HasManyRelationDeleteCascadeTests : OrmInMemoryTest
    {
        [Table]
        public class HasManyParent : IKeyedPersistent
        {
            private readonly List<HasManyDescendant> _hasManyDescendants = new List<HasManyDescendant>();

            [GuidPrimaryKey]
            public IKey Key { get; set; }

            [HasMany]
            public IEnumerable<HasManyDescendant> HasManyDescendants
            {
                get
                {
                    return _hasManyDescendants;
                }
            }

            public void AddHasManyDescendant(HasManyDescendant hasManyDescendant)
            {
                _hasManyDescendants.Add(hasManyDescendant);
            }

            public HasManyParent()
            {
                Key = AbstractKeyFactory.For<Guid>().New();
            }
        }

        [Table]
        public class HasManyDescendant : IKeyedPersistent
        {
            [GuidPrimaryKey]
            public IKey Key { get; set; }

            public HasManyDescendant()
            {
                Key = AbstractKeyFactory.For<Guid>().New();
            }
        }

        [TestMethod]
        public void HasManyRelation_DeleteCascades()
        {
            var parent = new HasManyParent();
            parent.AddHasManyDescendant(new HasManyDescendant());
            using (var unitOfWork = GetKeyedUnitOfWork<HasManyParent>())
            {
                unitOfWork.MakePersistent(parent);
            }
            using (var unitOfWork = GetKeyedUnitOfWork<HasManyParent>())
            {
                unitOfWork.Delete(parent.Key);
            }
            using (var unitOfWork = GetKeyedUnitOfWork<HasManyParent>())
            {
                Assert.IsFalse(unitOfWork.GetAll().Any(), "Parent wasn't deleted");
            }
            using (var unitOfWork = GetKeyedUnitOfWork<HasManyDescendant>())
            {
                Assert.IsFalse(unitOfWork.GetAll().Any(), "Descendant wasn't deleted");
            }
        }
    }
}
